import { uuid } from '@/utils'

export default {
  data () {
    return {
      // 右键后弹框
      visible: false,
      left: 0,
      top: 0,
    }
  },
  methods: {
    // 选中某一行的情况下右键操作
    onContextmenu (evt) {
      evt.preventDefault()
      if (this.readonly) return false

      let tr = evt.target
      while (tr) {
        if ((tr.tagName || '').toUpperCase() === 'TR') {
          break
        }
        tr = tr.parentNode
      }
      if (tr) {
        const menuMinWidth = 105
        const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
        const offsetWidth = this.$el.offsetWidth // container width
        const maxLeft = offsetWidth - menuMinWidth // left boundary
        const left = evt.clientX - offsetLeft + 15 // 15: margin right

        if (left > maxLeft) {
          this.left = maxLeft
        } else {
          this.left = left
        }

        this.top = evt.clientY - 100
        this.visible = true
      }
    },
    // 删除 rowIndex 行
    delRow () {
      const rowIndex = this.rowIndex
      this.$confirm('确定要删除这一行？').then(() => {
        this.lists.splice(rowIndex, 1)
        this.visible = false
      }).catch(() => {})
    },

    createAEmptyRow () {
      return (this.flattenColumns || []).map(v => ({
        key: v.prop,
        value: '',
        editable: true,
      }))
    },
    // 在 rowIndex 行前添加一行
    prependRow () {
      const rowIndex = this.rowIndex
      const emptyRow = this.createAEmptyRow()
      if (rowIndex > -1) {
        this.lists.splice(rowIndex, 0, {
          uuid: uuid(),
          data: [...emptyRow]
        })

        this.$nextTick(() => {
          this.initInputIndex()
        })
      }
      this.visible = false
    },

    // 在 rowIndex 行后添加一行
    appendRow () {
      const rowIndex = this.rowIndex
      const emptyRow = this.createAEmptyRow()
      if (rowIndex > -1) {
        this.lists.splice(rowIndex + 1, 0, {
          uuid: uuid(),
          data: [...emptyRow]
        })

        this.$nextTick(() => {
          this.initInputIndex()
        })
      }
      this.visible = false
    },
  }
}
